﻿using GameFramework;
using LitJson;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace VRLauncher.Editor.DataTableTools
{
    public class DataTableGeneratorWindow : EditorWindow
    {
        private string dirPath = "Assets/GameRes/DataTables"; // 你想要读取的文件夹路径
        private string fileRoot = "DataTableRoot.txt";
        private string fileRootPath => Path.Combine(dirPath, fileRoot);

        private List<string> dataTableFiles = new List<string>(); // 存储文件名
        private List<bool> toggles = new List<bool>(); // 存储对应的勾选状态

        private Vector2 scrollPosition; // 用于存储滚动视图的位置

        [MenuItem("VRLauncher/Generate DataTables Window")]
        public static void ShowWindow()
        {
            DataTableGeneratorWindow window = GetWindow<DataTableGeneratorWindow>("Generate DataTables");
            window.Show();
        }

        private void OnEnable()
        {
            if (Directory.Exists(dirPath))
            {
                string[] files = Directory.GetFiles(dirPath, "*.csv"); // 获取所有txt文件

                // 删除名为 fileRoot 的文件
                dataTableFiles = new List<string>(files.Where(file => Path.GetFileName(file) != fileRoot));

                var dataTableFilesInFileRoot = ReadFileRoot();

                toggles = dataTableFiles.Select(file =>
                {
                    var fileName = Path.GetFileName(file);
                    var config = dataTableFilesInFileRoot.FirstOrDefault(c => c.name == fileName);
                    return config != null ? config.isOn : true; // 如果找到了配置，使用配置中的isOn值，否则默认为true
                }).ToList();
            }
            else
            {
                Debug.LogError("Path does not exist: " + dirPath);
            }
        }

        private void OnGUI()
        {
            GUILayout.Label("Select DataTables to Generate", EditorStyles.boldLabel);

            // 显示抬头
            GUILayout.BeginHorizontal();
            GUILayout.Label("配置列表", GUILayout.Width(180)); // 配置项名称
            GUILayout.Label("是否勾选", GUILayout.Width(100)); // 勾选框
            GUILayout.EndHorizontal();

            // 使用 ScrollView 来防止文件超出窗口
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.Height(position.height - 100)); // 让文件区域可滚动
            for (int i = 0; i < dataTableFiles.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label(Path.GetFileName(dataTableFiles[i]), GUILayout.Width(200)); // 显示文件名
                bool newIsOn = EditorGUILayout.Toggle("", toggles[i], GUILayout.Width(30)); // 勾选框
                if (newIsOn != toggles[i])
                {
                    toggles[i] = newIsOn; // 更新勾选状态
                }
                GUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();

            if (GUILayout.Button("Generate DataTables"))
            {
                GenerateDataTables();
            }
        }

        private void OnDisable()
        {
            WriteFileRoot();
        }

        /// <summary>
        /// 读取总配置中的内容
        /// </summary>
        private List<DataTableConfig> ReadFileRoot()
        {
            List<DataTableConfig> dataTableFilesInFileRoot;

            if (File.Exists(fileRootPath))
            {
                dataTableFilesInFileRoot = JsonMapper.ToObject<List<DataTableConfig>>(File.ReadAllText(fileRootPath));
            }
            else
            {
                dataTableFilesInFileRoot = new List<DataTableConfig>();
            }

            return dataTableFilesInFileRoot;
        }

        /// <summary>
        /// 保存总配置到文件
        /// </summary>
        private void WriteFileRoot()
        {
            var configs = toggles.Select((isOn, index) => new DataTableConfig { name = Path.GetFileName(dataTableFiles[index]), isOn = isOn }).ToList();

            StringWriter stringWriter = new StringWriter();
            JsonWriter writer = new JsonWriter(stringWriter)
            {
                PrettyPrint = true, // 开启PrettyPrint模式
                IndentValue = 4 // 设置缩进值为4个空格
            };

            JsonMapper.ToJson(configs, writer);

            File.WriteAllText(fileRootPath, stringWriter.ToString(), System.Text.Encoding.UTF8);
            AssetDatabase.Refresh();
        }



        private void GenerateDataTables()
        {
            for (int i = 0; i < dataTableFiles.Count; i++)
            {
                if (toggles[i]) // 如果该文件被勾选
                {
                    string dataTableName = Path.GetFileNameWithoutExtension(dataTableFiles[i]);
                    DataTableProcessor dataTableProcessor = DataTableGenerator.CreateDataTableProcessor(dataTableName);

                    if (!DataTableGenerator.CheckRawData(dataTableProcessor, dataTableName))
                    {
                        Debug.LogError(Utility.Text.Format("Check raw data failure. DataTableName='{0}'", dataTableName));
                        continue;
                    }

                    DataTableGenerator.GenerateDataFile(dataTableProcessor, dataTableName);
                    DataTableGenerator.GenerateCodeFile(dataTableProcessor, dataTableName);
                }
            }

            AssetDatabase.Refresh();
        }
    }
}